package com.FH.organization.fileupload;

import com.FH.util.AccessDB;
import com.FH.util.FileProcess;
import com.FH.util.ResultDTO;
import com.FH.util.warnSrc;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import javax.ejb.Stateless;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by Administrator on 2016/8/9.
 */
@Stateless
public class FileUploadDAOImpl extends AccessDB implements FileUploadDAO {

    /**
     * 查询文件信息
     *
     * @param search
     * @param page
     * @param size
     * @return
     */
    @Override
    public ResultDTO getfileInfo(String search, String page, String size) {
        ResultDTO resultDTO = new ResultDTO();

        try {
            JSONObject json = new JSONObject(search);
            String existName = "0";

            //先查询数据库中是否存在字段
            String sqlexit = "select count(1) from file  where 1=1 ";

            String sql_w = "";//查询条件sql组合
            String sql_page = "";//分页组合

            Integer page_ok = Integer.parseInt(page);//将定义page、size的String类型转换成Integer类型
            Integer size_ok = Integer.parseInt(size);

            if (page.equals("1")) {
                sql_page = " limit 0," + size + "";
            } else {
                sql_page = " limit " + ((page_ok - 1) * size_ok + 1) + "," + size + "";
            }

            if (json.has("member_id")) {
                sql_w += " AND member_id ='" + json.getString("member_id") + "'";
            }

            if (json.has("expen_form_id")) {
                sql_w += " AND expen_form_id ='" + json.getString("expen_form_id") + "'";
            }
            if (json.has("filegui_id")) {
                sql_w += " AND filegui_id ='" + json.getString("filegui_id") + "'";
            }

            String sql_ok = sqlexit + sql_w + sql_page;//组合好的sql语句
            existName = getReportingToOne(sql_ok);

            List<String[]> seresult = new ArrayList<String[]>();

            List<FileUploadDTO> result = new ArrayList<FileUploadDTO>();

            if (!existName.equals("0")) {
                String sql = "SELECT file_id,file_addr,file_time,filegui_id,file_name FROM file WHERE  1=1" + sql_w + sql_page;
                //     String sql ="select * from finance_budget" ;
                seresult = this.getReportingTo(sql);

                for (int i = 0; i < seresult.size(); ++i) {
                    FileUploadDTO fileUploadDTO = new FileUploadDTO();


                    fileUploadDTO.setFile_id(seresult.get(i)[1]);
                    String[] image_path = this.getImage_path();
                    String image_pathSerAddr = image_path[2];//图片访问地址
                    fileUploadDTO.setFile_addr(image_pathSerAddr+seresult.get(i)[2]);
                    fileUploadDTO.setFile_time(seresult.get(i)[3]);
                    fileUploadDTO.setFilegui_id(seresult.get(i)[4]);
                    fileUploadDTO.setFiletype(seresult.get(i)[5]);
                    result.add(fileUploadDTO);
                }
            }
            if (seresult.size() != 0) {
                resultDTO.setStatus("90000");
                resultDTO.setDescritpion(warnSrc.get_success);
            } else {
                resultDTO.setStatus("90001");
                resultDTO.setDescritpion(warnSrc.get_fail);
            }
            resultDTO.setValues(result);

        } catch (JSONException e) {
            e.printStackTrace();

        }
        return resultDTO;
    }

    /**
     * 获取文件柜详情
     *
     * @return
     */
    @Override
    public ResultDTO getFileInfo() {

        ResultDTO res = new ResultDTO();
        List<String[]> seresult = new ArrayList<String[]>();
        ArrayList<FileUploadShowDTO> result = new ArrayList<FileUploadShowDTO>();

        // 查询SQL语句
        String GET_QUERY = "";
        GET_QUERY += "select * from filegui ";

        String get_count = "select count(*) from filegui ";
        String count = this.getReportingToOne(get_count);

        seresult = this.getReportingTo(GET_QUERY);

        for (int i = 0; i < seresult.size(); i++) {
            FileUploadShowDTO fileUploadShowDTO = new FileUploadShowDTO();
            fileUploadShowDTO.setFilegui_id(seresult.get(i)[1]);
            fileUploadShowDTO.setName(seresult.get(i)[2]);

            result.add(fileUploadShowDTO);
        }
        // 判断SQl是否执行成功
        if (seresult.size() != 0) {
            res.setValues(seresult);
            res.setStatus("90000");//
            res.setDescritpion(warnSrc.get_success);
        } else {
            res.setStatus("90001");//
            res.setDescritpion(warnSrc.get_fail);
        }
        res.setValues(result);
        return res;
    }

    /**
     * 添加文件柜信息
     *
     * @param dataDTO
     * @return
     */
    @Override
    public ResultDTO addfileguiInfo(FileUploadPullDTO dataDTO) {

        ResultDTO resultDTO = new ResultDTO();
        int resultls = 0;
        String file_insert = "";

        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
        //插入图片到附件
        // String id = getImage(dataDTO.getFilestream());
        // if (id != null) {

        file_insert += "insert into filegui(filegui_id,name) VALUES('" + uuid + "','" + dataDTO.getName() + "')";
        //插入业务表
        resultls = addReportingTo(file_insert);
        if (resultls != 0) {
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(warnSrc.add_success);
        } else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion(warnSrc.add_fail);
            //   }
//        } else {
//            resultDTO.setStatus("90001");
//            resultDTO.setDescritpion("报销单申请失败");
        }
        return resultDTO;
    }

    @Override
    public ResultDTO deletefileguiInfo(FileUploadPullDTO dataDTO) {
        //删除之前查询一下该表是否有记录
        String sql = "select count(1) from filegui where filegui_id='" + dataDTO.getFilegui_id() + "'";

        String existName = getReportingToOne(sql);

        int result = 0;

        ResultDTO resultDTO = new ResultDTO();

        if (!existName.equals("0")) {

            String QUERY = "";
            QUERY += "delete from filegui where filegui_id='" + dataDTO.getFilegui_id() + "'";

            result = this.addReportingTo(QUERY);
        }

        if (result != 0) {
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(warnSrc.delete_success);
            FileUploadDTO fileUploadDTO = new FileUploadDTO();
            fileUploadDTO.setFilegui_id(dataDTO.getFilegui_id() );
            deletefileInfo(fileUploadDTO);

        } else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion(warnSrc.delete_fail);
        }
        return resultDTO;
    }

    /**
     * 增加文件详情
     *
     * @param
     * @return
     */
    @Override
    public ResultDTO addfileInfo(FileUploadDTO dataDTO) {

        ResultDTO resultDTO = new ResultDTO();
        // TODO Auto-generated method stub
        String enpenform_image = "";
        //获取配置图片地址
        String[] image_path = this.getImage_path();
        String image_pathAddr = image_path[1];//服务器项目目录地址
        String image_pathSerAddr = image_path[2];//图片访问地址
        String imgDirct = image_pathAddr + "/file/" + dataDTO.getFileguiname();
        File f = new File(imgDirct);
        if (!f.exists()) {
            f.mkdirs();
            f.setWritable(true, false);
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");

        String imgPath = imgDirct + "/" + dataDTO.getFiletype();


        //base64字符串保存为图片
        boolean headImg = FileProcess.GenerateImage(dataDTO.getFilestream(), imgPath);
        FileProcess.newlog("执行头像图片储存方法，储存照片地址：" + imgPath + " 方法返回：" + headImg);
        int resultls = 0;
        int mresult = 0;

        String imgurl = "/file/" + dataDTO.getFileguiname() + "/" + dataDTO.getFiletype();

        //ArrayList<HeadPortaitDTO> result = new ArrayList<HeadPortaitDTO>();

        if (headImg) {
            //插入头像表
            enpenform_image += "insert into file(file_id,file_addr,file_time,filegui_id,file_name) values ('" + uuid + "','" + imgurl + "','" + df.format(new Date()) + "','" + dataDTO.getFilegui_id() + "','" + dataDTO.getFiletype() + "')";
            //执行sql
            resultls = addReportingTo(enpenform_image);
        }

        if (resultls != 0) {
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion("上传文件成功");
        } else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion("上传文件失败");
        }
        return resultDTO;
    }

    @Override
    public ResultDTO deletefileInfo(FileUploadDTO dataDTO) {
        String sql = "";
        //删除之前查询一下该表是否有记录
        if (dataDTO.getFilegui_id() != null && !dataDTO.getFilegui_id().equals("")) {
            sql = "select count(1) from file where filegui_id='" + dataDTO.getFilegui_id() + "'";
        }

        if (dataDTO.getFile_id() != null && !dataDTO.getFile_id().equals("")) {
            sql = "select count(1) from file where file_id='" + dataDTO.getFilegui_id() + "'";
        }

        String existName = getReportingToOne(sql);

        int result = 0;

        ResultDTO resultDTO = new ResultDTO();

        if (!existName.equals("0")) {

            String QUERY = "";
            if (dataDTO.getFilegui_id() != null && !dataDTO.getFilegui_id().equals("")) {
                QUERY += "delete from file where filegui_id='" + dataDTO.getFilegui_id() + "'";
            } else if (dataDTO.getFile_id() != null && !dataDTO.getFile_id().equals("")) {
                QUERY += "delete from file where file_id='" + dataDTO.getFile_id() + "'";
            }


            result = this.addReportingTo(QUERY);
        }

        if (result != 0) {
            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(warnSrc.delete_success);


        } else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion(warnSrc.delete_fail);
        }
        return resultDTO;
    }
}
